package com.mediacloud.app.newsmodule.fragment.baoliao.frag;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.format.Formatter;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baidu.location.Address;
import com.baidu.mapapi.search.core.PoiInfo;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eventTrack.TXReportManager;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.pictureselector.GlideEngine;
import com.mediacloud.app.assembly.util.FunKt;
import com.mediacloud.app.assembly.util.Utility;
import com.mediacloud.app.model.interfaces.DataInvokeCallBack;
import com.mediacloud.app.model.interfaces.IPermissionsAgree;
import com.mediacloud.app.model.interfaces.PermissionUtil;
import com.mediacloud.app.model.news.ArticleListData;
import com.mediacloud.app.model.news.NewBaoLiaoCountModel;
import com.mediacloud.app.model.utils.DefaultBgUtil;
import com.mediacloud.app.nav2.fragment.HqyNavFragment;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.fragment.activity.TipExplainActivity;
import com.mediacloud.app.newsmodule.fragment.baoliao.OnDeleteListener;
import com.mediacloud.app.newsmodule.fragment.baoliao.activity.BaoLiaoLocationActivity;
import com.mediacloud.app.newsmodule.fragment.baoliao.activity.BaoLiaoLocationActivityKt;
import com.mediacloud.app.newsmodule.fragment.baoliao.adapter.BaoLiaoAdapter;
import com.mediacloud.app.newsmodule.fragment.baoliao.adapter.BaoLiaoPreImageAdapter;
import com.mediacloud.app.newsmodule.fragment.baoliao.api.CMSApi;
import com.mediacloud.app.newsmodule.fragment.baoliao.api.CrmsApi;
import com.mediacloud.app.newsmodule.fragment.baoliao.api.ProgressRequestBody;
import com.mediacloud.app.newsmodule.fragment.baoliao.api.SpiderCmsApi;
import com.mediacloud.app.newsmodule.fragment.baoliao.api.SpiderCmsLowApi;
import com.mediacloud.app.newsmodule.fragment.baoliao.api.VMSApi;
import com.mediacloud.app.newsmodule.fragment.baoliao.model.BaoLiaoLayerField;
import com.mediacloud.app.newsmodule.fragment.baoliao.model.DraftModel;
import com.mediacloud.app.newsmodule.fragment.baoliao.model.LocalMediaWithState;
import com.mediacloud.app.newsmodule.fragment.baoliao.model.add.BaoLiaoColumnBean;
import com.mediacloud.app.newsmodule.fragment.baoliao.model.add.Catalog;
import com.mediacloud.app.newsmodule.fragment.baoliao.model.add.MulFileUpload;
import com.mediacloud.app.newsmodule.fragment.baoliao.model.add.ResourceMode;
import com.mediacloud.app.newsmodule.fragment.baoliao.model.add.ResourceModeNew;
import com.mediacloud.app.newsmodule.fragment.baoliao.model.add.SubmitRevelationReturnData;
import com.mediacloud.app.newsmodule.fragment.baoliao.model.add.SubmitVideoReturnData;
import com.mediacloud.app.newsmodule.fragment.baoliao.model.add.VideoReturnData;
import com.mediacloud.app.newsmodule.utils.LoginUtils;
import com.mediacloud.app.newsmodule.utils.NewsListDataInvoker;
import com.mediacloud.app.newsmodule.utils.ToastUtil;
import com.mediacloud.app.newsmodule.view.WrapLinearLayout;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;
import com.mediacloud.app.reslib.util.DataInvokeUtil;
import com.mediacloud.app.user.model.UserInfo;
import com.mediacloud.appcloud.project.gxapp.model.utils.ImageTools;
import com.tencent.mmkv.MMKV;
import com.utils.ClickUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cc.cloudist.acplibrary.ACProgressConstant;
import cc.cloudist.acplibrary.ACProgressFlower;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Yoake on 2018/7/25.
 */
@SuppressWarnings("ALL")
public class BaoLiaoFragment extends HqyNavFragment implements View.OnClickListener, OnDeleteListener, DataInvokeCallBack<ArticleListData> {


    private List<LocalMediaWithState> imageList;
    View baoliao_plus;
    private List<LocalMediaWithState> videoList;
    //private List<LocalMedia> audioList;
    private List<LocalMediaWithState> totalList;
    private RecyclerView recyclerView;
    private BaoLiaoAdapter mAdapter;
    private ArrayList<Catalog> catalogs;
    private TextView catalogText;
    private TextView hasNumber;
    private TextView totalNumber;
    // private RecyclerView listContainer;
    /**
     * 可以选择栏目的时候的根部就，为了方便关闭栏目选择
     */
    protected WrapLinearLayout catalogsContainer;
    private Catalog selectCatalog;
    private EditText phoneEditText, nameEditText, etRealName, etEmail;
    private TextView locationEditText;
    private TextView prompt;
    private ACProgressFlower dialog;
    private EditText mEditText;
    private List<ResourceMode> resourceModes;
    private List<ResourceModeNew> resourceModesNew;

    protected NewsListDataInvoker dataInvoker;
    BaoLiaoLayerField baoLiaoLayerField = null;
    LinearLayout columnLayout;
    LinearLayout llAgreement;
    View appfacSubmit;
    // ViewAdapter lanMuAdapter;
    int selectPosition = 0;

    /**
     * 爆料声明相关的几个view
     */
    View mBaioLiaoStatementContair;
    CheckBox mCbBaoLiaoStatement;
    TextView mTvBaoLiaoStatementTitle;
    private PoiInfo poiInfo;
    private BaoLiaoLayerField baoLiaoLayerField1;
    private DraftModel draftModel;
    private BaoLiaoPreImageAdapter baoLiaoPreImageAdapter;

    @Override
    public int getLayoutResID() {
        return R.layout.bao_liao_layout;
    }

    View popView;


    @Override
    public void initView() {
        //dialog = new SimpleDialog(getActivity());
        TXReportManager.getInstance().offer_clue();
        dialog = new ACProgressFlower.Builder(getActivity())
                .direction(ACProgressConstant.DIRECT_CLOCKWISE)
                .bgColor(0xff555555)
                .bgAlpha(0.9f)
                .sizeRatio(0.2f)
                .themeColor(Color.WHITE).fadeColor(Color.DKGRAY).build();
        catalogs = new ArrayList<>();
        resourceModes = new ArrayList<>();
        resourceModesNew = new ArrayList<>();
        columnLayout = findViewById(R.id.columnLayout);
        llAgreement = findViewById(R.id.llAgreement);
        appfacSubmit = findViewById(R.id.appfacSubmit);
        appfacSubmit.setOnClickListener(this);
        mEditText = findViewById(R.id.content);
        phoneEditText = findViewById(R.id.b_phone);
        locationEditText = findViewById(R.id.b_location);
        prompt = findViewById(R.id.prompt);
        prompt.setOnClickListener(this);
        nameEditText = findViewById(R.id.b_name);
        etRealName = findViewById(R.id.realName);
        etEmail = findViewById(R.id.email);
        imageList = new ArrayList<>();
        videoList = new ArrayList<>();
        //    audioList = new ArrayList<>();
        totalList = new ArrayList<>();
        baoliao_plus = findViewById(R.id.baoliao_plus);
        baoliao_plus.setOnClickListener(this);

        popView = LayoutInflater.from(getContext()).inflate(R.layout.baoliao_cat_pop, null);
        popView.findViewById(R.id.catalogLayout).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
//                popWindow.dismiss();
                if (event.getY() >= catalogsContainer.getMeasuredHeight()) {
                    if (popView.getParent() != null) {
                        ((ViewGroup) popView.getParent()).removeView(popView);
                    }
                }
                return false;
            }
        });

        catalogsContainer = popView.findViewById(R.id.catalogContainer);
        recyclerView = mRootView.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        mAdapter = new BaoLiaoAdapter(getActivity(), this);
        recyclerView.setAdapter(mAdapter);
        catalogText = findViewById(R.id.catalogText);
        totalNumber = findViewById(R.id.totalNumber);
        hasNumber = findViewById(R.id.hasNumber);
        columnLayout.setOnClickListener(v -> {
            BaoLiaoLanMuSheet f = new BaoLiaoLanMuSheet();
            Bundle bundle = new Bundle();
            bundle.putSerializable("CATALOG_LIST", catalogs);
            bundle.putSerializable("CATALOG", selectCatalog);
            f.setArguments(bundle);
            f.show(getChildFragmentManager(), "0");
        });
        mEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                hasNumber.setText(String.valueOf(mEditText.getText().length()));
                checkButton();
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        llAgreement.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), TipExplainActivity.class);
            if (selectCatalog != null && selectCatalog.getIntegralExplain() != null) {
                intent.putExtra("blAgreement", selectCatalog.getIntegralExplain().getTipExplain());
            }
            startActivity(intent);
        });


        View locationView = findViewById(R.id.linear_location);
        locationView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PermissionUtil.INSTANCE.invokeLocationPermission(requireActivity(), new IPermissionsAgree() {
                    @Override
                    public void onAgree() {
                        Intent intent = new Intent(getActivity(), BaoLiaoLocationActivity.class);
                        getActivity().startActivityForResult(intent, BaoLiaoLocationActivityKt.REQUEST_CODE);
                    }

                    @Override
                    public void onRefuse() {

                    }

                    @Override
                    public void hasPermissions() {
                        Intent intent = new Intent(getActivity(), BaoLiaoLocationActivity.class);
                        getActivity().startActivityForResult(intent, BaoLiaoLocationActivityKt.REQUEST_CODE);
                    }
                });

            }
        });
        mBaioLiaoStatementContair = findViewById(R.id.linear_bao_liao_statement);
        mCbBaoLiaoStatement = findViewById(R.id.cb_bao_liao_statement);
        mTvBaoLiaoStatementTitle = findViewById(R.id.tv_bao_liao_statement_title);
//        mTvBaoLiaoStatementTitle.setTextColor(AppFactoryGlobalConfig.getAppServerConfigInfo(getContext()).getMainColor());
        mTvBaoLiaoStatementTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //打开免责声明的对话框
                if (baoLiaoLayerField.getStatement().isRequire()) {
                    View dialogView = getLayoutInflater().inflate(R.layout.dialog_bao_liao_statement, null, false);
                    TextView tvStatementDetail = dialogView.findViewById(R.id.tv_statement_detail);
                    tvStatementDetail.setText(baoLiaoLayerField.getStatement().getContent());
                    TextView tvStatementTitle = dialogView.findViewById(R.id.tv_statement_title);
                    tvStatementTitle.setText(baoLiaoLayerField.getStatement().getTitle());
                    TextView tvStatementKnown = dialogView.findViewById(R.id.tv_known);
                    final AlertDialog alertDialog = new AlertDialog.Builder(getContext(), R.style.red_envelope_theme_dialog)
                            .create();
                    alertDialog.show();
                    Window window = alertDialog.getWindow();
                    if (window != null) {
                        window.setContentView(dialogView);
                        WindowManager.LayoutParams attr = window.getAttributes();
                        if (attr != null) {
                            WindowManager windowManager = window.getWindowManager();
                            Point outSize = new Point();
                            windowManager.getDefaultDisplay().getRealSize(outSize);
                            attr.height = outSize.y;
                            attr.width = outSize.x;
                            attr.gravity = Gravity.CENTER;//设置dialog 在布局中的位置
                        }
                        window.setAttributes(attr);
                    }
                    tvStatementKnown.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            alertDialog.dismiss();
                        }
                    });
                }
            }
        });

        String baoliao_draft = MMKV.defaultMMKV().getString("baoliao_draft", "");
        if (!TextUtils.isEmpty(baoliao_draft)) {
            draftModel = GsonUtils.fromJson(baoliao_draft, DraftModel.class);
            selectCatalog = draftModel.getCatalog();
            catalogText.setText(selectCatalog.getName());
            mEditText.setText(draftModel.getContent());
            hasNumber.setText(String.valueOf(mEditText.getText().length()));
            totalNumber.setText(MessageFormat.format("/{0}", selectCatalog.getIntegralExplain().getTipTextLimit()));
            phoneEditText.setText(draftModel.getPhoneNum());
            nameEditText.setText(draftModel.getUserName());
            etRealName.setText(draftModel.getRealName());
            etEmail.setText(draftModel.getEmail());
            totalList.addAll(draftModel.getImgs());
            for (int i = 0; i < draftModel.getImgs().size(); i++) {
                if (draftModel.getImgs().get(i).getLocalMedia().getRealPath().endsWith("mp4")) {
                    videoList.add(draftModel.getImgs().get(i));
                } else {
                    imageList.add(draftModel.getImgs().get(i));
                }
            }
            mAdapter.setImgMaxSize(selectCatalog.getIntegralExplain().getTipImageSizeLimit() * 1000000);
            mAdapter.setVideoMaxSize(selectCatalog.getIntegralExplain().getTipVideoSizeLimit() * 1000000);
            mAdapter.setSelectList(draftModel.getImgs());
            checkButton();
        } else {
            appfacSubmit.setEnabled(false);
            appfacSubmit.setBackground(DefaultBgUtil.generateRoundShapeDrawable(getResources().getDimensionPixelSize(R.dimen.dimen3), Color.parseColor("#4DE41D1D")));
        }
        UserInfo userInfo = UserInfo.getUserInfo(requireContext());
        phoneEditText.setText(userInfo.getMobile());
        nameEditText.setText(userInfo.getNickname());
    }

    private boolean imgVideoFit = true;
    private boolean contentFit = true;

    /**
     * 是否超过文字长度 图片 视频大小限制
     */
    private void checkButton() {
        if (selectCatalog != null && selectCatalog.getIntegralExplain() != null) {
            if (mEditText.getText().length() <= selectCatalog.getIntegralExplain().getTipTextLimit()) {
                hasNumber.setTextColor(ContextCompat.getColor(requireContext(), R.color._222));
                contentFit = true;
            } else {
                hasNumber.setTextColor(ContextCompat.getColor(requireContext(), R.color.cctv7_red));
                contentFit = false;
            }
        }

        if (contentFit) {
            appfacSubmit.setEnabled(true);
            if (mEditText.getText().length() > 0) {
                appfacSubmit.setBackground(DefaultBgUtil.generateRoundShapeDrawable(getResources().getDimensionPixelSize(R.dimen.dimen3), DefaultBgUtil.getTintColor(getActivity())));
            } else {
                appfacSubmit.setBackground(DefaultBgUtil.generateRoundShapeDrawable(getResources().getDimensionPixelSize(R.dimen.dimen3), Color.parseColor("#4DE41D1D")));
            }
        } else {
            contentFit = true;
            appfacSubmit.setEnabled(false);
            appfacSubmit.setBackground(DefaultBgUtil.generateRoundShapeDrawable(getResources().getDimensionPixelSize(R.dimen.dimen3), Color.parseColor("#4DE41D1D")));
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCatalogSelected(BLCatalogEvent event) {
        selectCatalog = event.getCatalog();
        catalogText.setText(selectCatalog.getName());
        hasNumber.setText(String.valueOf(mEditText.getText().length()));
        totalNumber.setText(MessageFormat.format("/{0}", selectCatalog.getIntegralExplain().getTipTextLimit()));
        mEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(selectCatalog.getIntegralExplain().getTipTextLimit())});
        mAdapter.setImgMaxSize(selectCatalog.getIntegralExplain().getTipImageSizeLimit() * 1000000);
        mAdapter.setVideoMaxSize(selectCatalog.getIntegralExplain().getTipVideoSizeLimit() * 1000000);
        mAdapter.notifyDataSetChanged();
        if (mEditText.getText().length() <= selectCatalog.getIntegralExplain().getTipTextLimit()) {
            hasNumber.setTextColor(ContextCompat.getColor(requireContext(), R.color._222));
        } else {
            hasNumber.setTextColor(ContextCompat.getColor(requireContext(), R.color.cctv7_red));
        }
        checkButton();
    }

    protected void hideKeyBroad() {
        final View v = getActivity().getWindow().peekDecorView();
        if (v != null && v.getWindowToken() != null) {
            InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }

    @Override
    protected void initOther() {
        dataInvoker = new NewsListDataInvoker(this);
        String catalogID = getArguments().getString("catalogId", "");
        dataInvoker.getContentListWithAd(catalogID, 1, 2, null);
    }

    @Override
    public void onClick(View v) {


        if (v == baoliao_plus) {
            showOpenImgDialog();
        } else if (v == catalogText) {
            if (popView.getParent() == null) {
                int[] location = new int[2];
                //   viewLine1.getLocationOnScreen(location);
                //   int yPosition = location[1];//-(location[1]-heightMoreBtnView);
              /*  View appfacContainer=popView.findViewById(R.id.appfacContainer);
                RelativeLayout.LayoutParams layoutParams= (RelativeLayout.LayoutParams) appfacContainer.getLayoutParams();
                layoutParams.topMargin=yPosition;
                appfacContainer.setLayoutParams(layoutParams);*/
                RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
                //   layoutParams.topMargin = viewLine1.getTop();
                mRootView.addView(popView, layoutParams);
//                popWindow.showAsDropDown(getActivity().getWindow().getDecorView(), 0, yPosition);
            } else {
                ((ViewGroup) popView.getParent()).removeView(popView);
            }
        } else if (v == appfacSubmit) {
            if (totalList != null && totalList.size() > 0) {
                for (int i = 0; i < totalList.size(); i++) {
                    File fl = new File(totalList.get(i).getLocalMedia().getRealPath());
                    if (selectCatalog != null && selectCatalog.getIntegralExplain() != null) {
                        if (fl.length() > ((PictureMimeType.getMimeType(totalList.get(i).getLocalMedia().getMimeType()) == PictureConfig.TYPE_VIDEO) ? selectCatalog.getIntegralExplain().getTipVideoSizeLimit() * 1000000 : selectCatalog.getIntegralExplain().getTipImageSizeLimit() * 1000000)) {
                            imgVideoFit = false;
                        }
                    }
                }
            }
            if (imgVideoFit) {
                onSubmit();
            } else {
//                onSubmit();
                imgVideoFit = true;
                tipImageDialog("您上传的图片/视频大小超过限制", selectCatalog.getIntegralExplain().getGtaddTipoffMaxNumMessage());
            }
        } else if (v == prompt) {
            if (selectCatalog != null && selectCatalog.getIntegralExplain() != null) {
                tipDialog();
            }
        }
    }

    protected void showOpenImgDialog() {
        BottomSheetDialog dialog = new BottomSheetDialog(getContext());
        //2、设置布局
        View view = View.inflate(getContext(), R.layout.open_img_dialog_view, null);

        //拿到两个按钮
        View tv_select_image = view.findViewById(R.id.tv_select_image);
        TextView tv_select_video = view.findViewById(R.id.tv_select_video);
        TextView cancle = view.findViewById(R.id.cancle);
        dialog.setContentView(view);
        tv_select_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PermissionUtil.INSTANCE.invokeStoragePermission(requireActivity(), new IPermissionsAgree() {
                    @Override
                    public void onAgree() {
                        permissionsOK(PictureConfig.TYPE_IMAGE);
                        dialog.dismiss();
                    }

                    @Override
                    public void onRefuse() {

                    }

                    @Override
                    public void hasPermissions() {
                        permissionsOK(PictureConfig.TYPE_IMAGE);
                        dialog.dismiss();
                    }
                });
            }
        });
        tv_select_video.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PermissionUtil.INSTANCE.invokeStoragePermission(requireActivity(), new IPermissionsAgree() {
                    @Override
                    public void onAgree() {
                        permissionsOK(PictureConfig.TYPE_VIDEO);
                        dialog.dismiss();
                    }

                    @Override
                    public void onRefuse() {

                    }

                    @Override
                    public void hasPermissions() {
                        permissionsOK(PictureConfig.TYPE_VIDEO);
                        dialog.dismiss();
                    }
                });
            }
        });

        cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    private void tipImageDialog(String tip, String content) {
        Dialog dialog = new Dialog(requireContext(), R.style.CustomDatePickerDialog);
        //2、设置布局
        View view = View.inflate(requireContext(), R.layout.dialog_baoliao_image_size_tip, null);
        TextView title = view.findViewById(R.id.title);
        TextView tvContent = view.findViewById(R.id.tvContent);
        title.setText(tip);
        tvContent.setText(content);
        dialog.setContentView(view);
        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(true);
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        Window window = dialog.getWindow();
        //设置弹出位置
        window.setGravity(Gravity.CENTER);
        dialog.show();
    }

    private void tipDialog() {
        Dialog dialog = new Dialog(requireContext(), R.style.CustomDatePickerDialog);
        //2、设置布局
        View view = View.inflate(requireContext(), R.layout.popup_window_baoliao_prompt, null);
        TextView confirm = view.findViewById(R.id.confirm);
        TextView imgSize = view.findViewById(R.id.imgSize);
        TextView imgNum = view.findViewById(R.id.imgNum);
        TextView videoSize = view.findViewById(R.id.videoSize);
        TextView videoNum = view.findViewById(R.id.videoNum);
        TextView userNum = view.findViewById(R.id.userNum);
        View rootview = view.findViewById(R.id.rootview);
        if (selectCatalog == null) {
            selectCatalog = new Catalog();
        }
        imgSize.setText(selectCatalog.getIntegralExplain().getTipImageSizeLimit() + "兆/张");
        imgNum.setText(selectCatalog.getIntegralExplain().getTipImageNumLimit() + "张");
        videoSize.setText(selectCatalog.getIntegralExplain().getTipVideoSizeLimit() + "兆/个");
        videoNum.setText(selectCatalog.getIntegralExplain().getTipVideoNumLimit() + "个");
        userNum.setText("每用户每天" + selectCatalog.getIntegralExplain().getAddTipoffMaxNum() + "次");
        confirm.setText("确定");
        dialog.setContentView(view);
        dialog.setCancelable(true);
        rootview.setOnClickListener(view1 -> {
            dialog.cancel();
        });
        confirm.setOnClickListener(view1 -> {
            dialog.cancel();
        });

        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        Window window = dialog.getWindow();
        //设置弹出位置
        window.setGravity(Gravity.CENTER);
        //设置弹出动画
//        window.setWindowAnimations(R.style.dialogstyle);
        //设置对话 框大小
        window.setLayout(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
        );
        dialog.show();

    }

    private void preImagesDialog(int selectPosition) {
        Dialog dialog = new Dialog(requireContext(), R.style.CustomDatePickerDialog);
        //2、设置布局
        View view = View.inflate(requireContext(), R.layout.dialog_bao_liao_image_pre_layout, null);
        RecyclerView recyclerView = view.findViewById(R.id.recyclerView);
        baoLiaoPreImageAdapter = new BaoLiaoPreImageAdapter();
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        recyclerView.setAdapter(baoLiaoPreImageAdapter);
        //加在setAdapter后面
        PagerSnapHelper snapHelper = new PagerSnapHelper();
        snapHelper.attachToRecyclerView(recyclerView);
        baoLiaoPreImageAdapter.setTotalSize(mAdapter.getImagesList().size());
        baoLiaoPreImageAdapter.setNewData(mAdapter.getImagesList());
        baoLiaoPreImageAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.ivImage || view.getId() == R.id.rootView) {
                    dialog.dismiss();
                } else {
                    LocalMedia localMedia = mAdapter.getImagesList().get(position);
                    for (int i = 0; i < totalList.size(); i++) {
                        if (totalList.get(i).getLocalMedia().getCompressPath().equals(localMedia.getCompressPath())) {
                            totalList.remove(i);
                        }
                    }
                    mAdapter.setSelectList(totalList);
                    baoLiaoPreImageAdapter.setTotalSize((mAdapter.getImagesList().size()));
                    baoLiaoPreImageAdapter.setNewData(mAdapter.getImagesList());
                    if (mAdapter.getImagesList().size() < 1) {
                        dialog.dismiss();
                    }
                }

            }
        });
        LocalMediaWithState localMediaWithState = mAdapter.getSelectList().get(selectPosition);
        LocalMedia localMedia = localMediaWithState.getLocalMedia();
        for (int i = 0; i < mAdapter.getImagesList().size(); i++) {
            if (!TextUtils.isEmpty(mAdapter.getImagesList().get(i).getCompressPath()) && mAdapter.getImagesList().get(i).getCompressPath().equals(localMedia.getCompressPath())) {
                recyclerView.scrollToPosition(i);
                break;
            }
        }
        dialog.setContentView(view);
        dialog.setCancelable(true);
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        Window window = dialog.getWindow();
        //设置弹出位置
        window.setGravity(Gravity.CENTER);
        //设置弹出动画
//        window.setWindowAnimations(R.style.dialogstyle);
        //设置对话 框大小
        window.setLayout(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
        );
        dialog.show();
    }


    protected void permissionsOK(int type) {
        if (selectCatalog == null || selectCatalog.getIntegralExplain() == null) {
            return;
        }
        if (type == PictureConfig.TYPE_IMAGE) {
            if (imageList.size() >= selectCatalog.getIntegralExplain().getTipImageNumLimit()) {
                ToastUtil.show(getActivity(), "最多只能上传" + selectCatalog.getIntegralExplain().getTipImageNumLimit() + "张图片");
                return;
            }
            PictureSelector.create(requireActivity())
                    .openGallery(PictureMimeType.ofImage())
                    .imageEngine(GlideEngine.createGlideEngine())
                    .maxSelectNum(selectCatalog.getIntegralExplain().getTipImageNumLimit() - imageList.size())// - audioList.size())
                    .imageSpanCount(3)
                    .enableCrop(false)
                    .cropCompressQuality(70)
                    .compress(true)
                    .minimumCompressSize(800)
                    .isGif(true)
                    .previewImage(false)
                    .isCamera(true)
                    .forResult(PictureConfig.TYPE_IMAGE);


        } else if (type == PictureConfig.TYPE_VIDEO) {
            if (videoList.size() >= selectCatalog.getIntegralExplain().getTipVideoNumLimit()) {
                ToastUtil.show(getActivity(), "最多只能上传" + selectCatalog.getIntegralExplain().getTipVideoNumLimit() + "个视频");
                return;
            }
            PictureSelector.create(requireActivity())
                    .openGallery(PictureMimeType.ofVideo())
                    .imageEngine(GlideEngine.createGlideEngine())
                    .maxSelectNum(selectCatalog.getIntegralExplain().getTipVideoNumLimit() - videoList.size())
                    .imageSpanCount(3)
                    .isCamera(true)
                    .selectionMode(PictureConfig.SINGLE)
                    .previewVideo(false)
                    // .selectionMedia(videoList)
                    .forResult(PictureConfig.TYPE_VIDEO);


        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == BaoLiaoLocationActivityKt.REQUEST_CODE && data != null) {
            poiInfo = data.getParcelableExtra(BaoLiaoLocationActivityKt.REQUEST_KEY);
            if (poiInfo != null) {
                locationEditText.setText(poiInfo.address);
            }
            return;
        }
        if (data != null) {
            if (selectCatalog != null && selectCatalog.getIntegralExplain() != null) {
                mAdapter.setImgMaxSize(selectCatalog.getIntegralExplain().getTipImageSizeLimit() * 1000000);
                mAdapter.setVideoMaxSize(selectCatalog.getIntegralExplain().getTipVideoSizeLimit() * 1000000);
            }
            String total = Formatter.formatFileSize(requireContext(), 1000000);
            if (requestCode == PictureConfig.TYPE_IMAGE) {
                List<LocalMedia> mediaList = PictureSelector.obtainMultipleResult(data);
                buildLocalMediaList(mediaList, imageList);
            } else if (requestCode == PictureConfig.TYPE_VIDEO) {
                videoList.clear();
                List<LocalMedia> mediaList = PictureSelector.obtainMultipleResult(data);
                buildLocalMediaList(mediaList, videoList);
            }

            totalList.clear();
            totalList.addAll(imageList);
            totalList.addAll(videoList);
            mAdapter.setSelectList(totalList);
            checkButton();
        }
    }

    private void buildLocalMediaList(List<LocalMedia> mediaList, List<LocalMediaWithState> videoList) {
        if (mediaList != null && mediaList.size() != 0) {
            for (LocalMedia localMedia : mediaList) {
                videoList.add(new LocalMediaWithState(localMedia));
            }
        }
    }

    @Override
    public void onDelete(LocalMediaWithState deleteItem) {
        totalList.clear();
        imageList.clear();
        videoList.clear();
//        audioList.clear();
        totalList.addAll(mAdapter.getSelectList());
        for (LocalMediaWithState media : totalList) {
            if (PictureMimeType.getMimeType(media.getLocalMedia().getMimeType()) == PictureConfig.TYPE_IMAGE) {
                imageList.add(media);
            } else if (PictureMimeType.getMimeType(media.getLocalMedia().getMimeType()) == PictureConfig.TYPE_VIDEO) {
                videoList.add(media);
            }
        }
        checkButton();
    }

    @Override
    public void onPreImages(int position) {
        preImagesDialog(position);


//        ArrayList<String> strings = new ArrayList<>();
//        List<LocalMedia> imagesList = mAdapter.getImagesList();
//        for (int i = 0; i < imagesList.size(); i++) {
//            strings.add(imagesList.get(i).getCompressPath());
//        }
//        Intent intent = new Intent(requireContext(), BaoLiaoPreImagesActivity.class);
//        intent.putStringArrayListExtra("Data",strings);
//        intent.putExtra("position",position);
//        getContext().startActivity(intent);

    }


    @Override
    public void success(ArticleListData data) {
        if (data.state) {
            try {
                baoLiaoLayerField = BaoLiaoLayerField.parseMeta(data.orginData.optJSONObject("data").optJSONObject("meta"));
                //必填的時候進來才給他設置這個值
                if (baoLiaoLayerField != null && baoLiaoLayerField.locationMust && AppFactoryGlobalConfig.getAddress() != null && !TextUtils.isEmpty(AppFactoryGlobalConfig.getAddressStr())) {
                    locationEditText.setText(AppFactoryGlobalConfig.getAddressStr());
                }
                //必填判斷
                if (baoLiaoLayerField != null && baoLiaoLayerField.realNameMust) {
                    nameEditText.setHint(R.string.must_input_nickname);
                } else {
                    nameEditText.setHint(R.string.can_empty_nickname);
                }
                if (baoLiaoLayerField.getStatement().isRequire()) {
                    mTvBaoLiaoStatementTitle.setText(String.format("《%s》", baoLiaoLayerField.getStatement().getTitle()));
                    mBaioLiaoStatementContair.setVisibility(View.VISIBLE);
                }
                /**
                 * 获取爆料栏目
                 */
                SpiderCmsApi.getSpiderCmsApiJson(getActivity()).getRevelationCatalogList(getString(R.string.tenantid),AppFactoryGlobalConfig.getAppServerConfigInfo(getContext()).getCms_app_id()).enqueue(new Callback<JSONObject>() {
                    @Override
                    public void onResponse(Call<JSONObject> call, Response<JSONObject> response) {
                        if (getActivity() == null)
                            return;
                        if (response.body() != null) {
                            BaoLiaoColumnBean catalogListBeen = GsonUtils.fromJson(response.body().toString(), BaoLiaoColumnBean.class);
                            if (catalogListBeen != null && catalogListBeen.getData() != null) {
                                List<Catalog> cmsCatalog = catalogListBeen.getData();
                                catalogs.clear();
                                String selectCatalogIds = baoLiaoLayerField.getSelect_catalog_id();
                                if (!"0".equals(selectCatalogIds)) {
                                    if (!TextUtils.isEmpty(selectCatalogIds)) {
                                        /**
                                         * 以前的限制条件，如果要改回去，注释打开即可
                                         */
                                        final String[] catalogString = selectCatalogIds.split(",");
                                        for (String s : catalogString) {
                                            for (Catalog catalog : cmsCatalog) {
                                                if (s.equals(catalog.getId() + "")) {
                                                    catalogs.add(catalog);
                                                    break;
                                                }
                                            }
                                        }

                                        if (catalogs.size() == 0 || catalogs.size() == 1) {
                                            catalogs.addAll(cmsCatalog);
                                        }
                                    } else {
                                        catalogs.clear();
                                        catalogs.addAll(cmsCatalog);
                                    }
                                } else {
                                    catalogs.clear();
                                    catalogs.addAll(cmsCatalog);
                                }
                                if (catalogs.size() > 0 && TextUtils.isEmpty(catalogText.getText().toString())) {
                                    selectCatalog = catalogs.get(0);
                                    catalogText.setText(selectCatalog.getName());
                                    hasNumber.setText(String.valueOf(mEditText.getText().length()));
                                    totalNumber.setText(MessageFormat.format("/{0}", selectCatalog.getIntegralExplain().getTipTextLimit()));
                                    mAdapter.setImgMaxSize(selectCatalog.getIntegralExplain().getTipImageSizeLimit() * 1000000);
                                    mAdapter.setVideoMaxSize(selectCatalog.getIntegralExplain().getTipVideoSizeLimit() * 1000000);
                                }

                            } else {
                                Utility.showToast(getActivity(), getString(R.string.baoliao_get_catalog_fail));
                                Drawable drawable = ContextCompat.getDrawable(getContext(), R.drawable.b_chose);
                                drawable = Utility.tintDrawable(AppFactoryGlobalConfig.getAppServerConfigInfo(getContext()).getMainColor(), drawable);
                                catalogText.setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null);
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<JSONObject> call, Throwable t) {
                        if (getActivity() == null)
                            return;
                        Utility.showToast(getActivity(), getString(R.string.baoliao_get_catalog_fail));
                    }
                });


            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public void fault(Object data) {

    }

    public void onSubmit() {
        TXReportManager.getInstance().big_break();
        UserInfo userInfo = UserInfo.getUserInfo(getActivity());
        if (!userInfo.isLogin()) {
            LoginUtils.request_source = "爆料";
            LoginUtils.invokeLogin(getActivity());
        } else {
            baoLiaoLayerField1 = baoLiaoLayerField;
            if (baoLiaoLayerField1 != null) {
                if (baoLiaoLayerField.contentIsMust) {
                    String content = mEditText.getText().toString();
                    if (TextUtils.isEmpty(content)) {
                        ToastUtil.show(getActivity(), "请填写内容");
                        return;
                    }
                }

                if (baoLiaoLayerField.phoneMust) {
                    String phone = phoneEditText.getText().toString();
                    if (TextUtils.isEmpty(phone)) {
                        ToastUtil.show(getActivity(), "请填写正确的手机号码");
                        return;
                    }
                }

                if (baoLiaoLayerField.locationMust) {
                    String location = locationEditText.getText().toString();
                    if (TextUtils.isEmpty(location)) {
                        ToastUtil.show(getActivity(), "请填写地点");
                        return;
                    }
                }

                if (baoLiaoLayerField.realNameMust) {
                    String name = nameEditText.getText().toString();
                    if (TextUtils.isEmpty(name)) {
                        ToastUtil.show(getActivity(), "请填写您的昵称");
                        return;
                    }
                }
                /*if (baoLiaoLayerField.getStatement().isRequire()) {
                    if (!mCbBaoLiaoStatement.isChecked()) {
                        ToastUtil.show(getActivity(), String.format("请先阅读并同意《%s》", baoLiaoLayerField.getStatement().getTitle()));
                        return;
                    }
                }*/
            } else {
                String content = mEditText.getText().toString();
                if (TextUtils.isEmpty(content)) {
                    ToastUtil.show(getActivity(), "请填写内容");
                    return;
                }
               /* String name = nameEditText.getText().toString();
                if (TextUtils.isEmpty(name)) {
                    ToastUtil.show(getActivity(), "请填写您的昵称");
                    return;
                }*/
            }
            String phone = phoneEditText.getText().toString();
            if (!TextUtils.isEmpty(phone)) {
                boolean isPhone = Utility.isMobileNO(phone);
                if (!isPhone) {
                    ToastUtil.show(getActivity(), "请填写正确的手机号码");
                    return;
                }
            }
            String content = mEditText.getText().toString();
            if (!TextUtils.isEmpty(content) && selectCatalog != null) {
                if (content.length() > selectCatalog.getIntegralExplain().getTipTextLimit()) {
                    tipImageDialog("最多输入" + selectCatalog.getIntegralExplain().getTipTextLimit() + "个字符", selectCatalog.getIntegralExplain().getGtaddTipoffMaxNumMessage());
                    return;
                }
            }
            if (selectCatalog != null && videoList.size() > selectCatalog.getIntegralExplain().getTipVideoNumLimit()) {
                tipImageDialog("最多上传" + selectCatalog.getIntegralExplain().getTipVideoNumLimit() + "个视频", selectCatalog.getIntegralExplain().getGtaddTipoffMaxNumMessage());
                return;
            }
            if (selectCatalog != null && imageList.size() > selectCatalog.getIntegralExplain().getTipImageNumLimit()) {
                tipImageDialog("最多上传" + selectCatalog.getIntegralExplain().getTipImageNumLimit() + "张图片", selectCatalog.getIntegralExplain().getGtaddTipoffMaxNumMessage());
                return;
            }
            SpiderCmsApi.getSpiderCmsApi(getContext()).getSubmitTipoffCount(getString(R.string.tenantid), selectCatalog.getId(), UserInfo.getUserInfo(requireContext()).getUserid())
                    .observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io())
                    .subscribe(new Observer<NewBaoLiaoCountModel>() {
                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onNext(NewBaoLiaoCountModel newBaoLiaoCountModel) {
                            NewBaoLiaoCountModel.DataBean data = newBaoLiaoCountModel.getData();
                            if (!data.isOverstep()) {
                                dialog.show();
                                dialog.setCanceledOnTouchOutside(false);
                                resourceModes.clear();
                                resourceModesNew.clear();

                                videoList.clear();
                                imageList.clear();
                                for (LocalMediaWithState localMedia : totalList) {
                                    if (PictureMimeType.isHasVideo(localMedia.getLocalMedia().getMimeType())) {
                                        videoList.add(localMedia);
                                    } else if (PictureMimeType.isHasImage(localMedia.getLocalMedia().getMimeType())) {
                                        imageList.add(localMedia);
                                    }
                                }
                                if (imageList.size() == 0 && videoList.size() == 0) {
                                    addRevelation();
                                } else {
//                                    submitImage();
                                    submitVideo();
                                }
                            } else {
                                tipImageDialog("超出次数限制", selectCatalog.getIntegralExplain().getGtaddTipoffMaxNumMessage());
                            }
                        }

                        @Override
                        public void onError(Throwable e) {
                            e.printStackTrace();
                        }

                        @Override
                        public void onComplete() {

                        }
                    });

        }
    }


    boolean isVideo(LocalMedia localMedia) {
        return PictureMimeType.isHasVideo(localMedia.getMimeType());
    }

    /**
     * 量上传图片
     */
    private void submitImage() {
        if (imageList.size() == 0) {
            return;
        }
        if (imageList.size() > 0) {
            upImageLoadLocalMedia.clear();
            upImageLoadLocalMedia.addAll(imageList);
        }

        if (upImageLoadLocalMedia.size() > 0) {
            fileList.clear();
            imageProgressMap.clear();
            if (upImageLoadLocalMedia.get(0).getLocalMedia().isCompressed()) {
                fileList.put(upImageLoadLocalMedia.get(0), new File(upImageLoadLocalMedia.get(0).getLocalMedia().getCompressPath()));
            } else {
                fileList.put(upImageLoadLocalMedia.get(0), new File(upImageLoadLocalMedia.get(0).getLocalMedia().getPath()));
            }
            imageProgressMap.put(upImageLoadLocalMedia.get(0), new Progress(upImageLoadLocalMedia.get(0)));
            upLoadImageSingle();
        }
    }

    List<LocalMediaWithState> upImageLoadLocalMedia = new ArrayList<>();
    List<String> needList = new ArrayList<>();
    Map<LocalMediaWithState, File> fileList = new HashMap<>();
    Map<LocalMediaWithState, ProgressRequestBody.UploadCallbacks> imageProgressMap = new HashMap<>();

    private void upLoadImageSingle() {

        Map<String, RequestBody> map = new HashMap<>();
        map.put("TenantID", CMSApi.convertToRequestBody(getString(R.string.tenantid)));
        Log.e("upLoadImageSingle", +fileList.get(upImageLoadLocalMedia.get(0)).length() / 1024 + "k " + fileList.get(upImageLoadLocalMedia.get(0)).getPath());
//        CMSApi.getBlApi().uploadImg(map, CMSApi.filesToMultipartBodyParts(fileList, imageProgressMap)).enqueue(new Callback<SubmitImageReturnData>() {
        for (LocalMediaWithState loca : upImageLoadLocalMedia) {
            String tempFilePath;
            if (!TextUtils.isEmpty(loca.getLocalMedia().getCompressPath())) {
                tempFilePath = loca.getLocalMedia().getCompressPath();
            } else {
                if (!TextUtils.isEmpty(loca.getLocalMedia().getAndroidQToPath())) {
                    tempFilePath = loca.getLocalMedia().getAndroidQToPath();
                } else {
                    tempFilePath = loca.getLocalMedia().getPath();
                }
            }
            if (FileUtils.isFile(tempFilePath)) {
                long size = ImageTools.getFileSize(tempFilePath);
                if (size > 2 * 1048576) {
                    String filePath = ImageTools.compressImage(tempFilePath, 80);
                    if (!TextUtils.isEmpty(filePath)) {
                        needList.add(filePath);
                    }
                } else if (size > 0) {
                    needList.add(tempFilePath);
                }
            }
        }
        for (String path : needList) {
            File file = new File(path);
            RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpg"), file);
            MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
            DataInvokeUtil.ziMeiTiApi.revealFileUploadImage(body).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<Response<JSONObject>>() {
                        @Override
                        public void onSubscribe(@NotNull Disposable d) {

                        }

                        @Override
                        public void onNext(@NotNull Response<JSONObject> response) {
                            if (getActivity() == null)
                                return;
                            try {
                                JSONObject jsonObject = response.body();
                                
                                if (jsonObject.optBoolean("state")) {
                                    JSONObject data = jsonObject.optJSONObject("data");
                              
                                    String src = data.optString("full_src");
                                    String fileName = data.optString("file_name");
                                    String type = "image";
                                    ResourceMode mode = new ResourceMode(src, fileName, 1, "");
                                    ResourceModeNew modeNew = new ResourceModeNew(type, src, "", "");
                                    resourceModes.add(mode);
                                    resourceModesNew.add(modeNew);
                                    if (upImageLoadLocalMedia.size() > 0) {
                                        upImageLoadLocalMedia.remove(0);
                                    }
                                    if (upImageLoadLocalMedia.size() > 0) {
                                        fileList.clear();
                                        imageProgressMap.clear();
                                        imageProgressMap.put(upImageLoadLocalMedia.get(0), new Progress(upImageLoadLocalMedia.get(0)));
                                        if (upImageLoadLocalMedia.get(0).getLocalMedia().isCompressed()) {
                                            fileList.put(upImageLoadLocalMedia.get(0), new File(upImageLoadLocalMedia.get(0).getLocalMedia().getCompressPath()));
                                        } else {
                                            fileList.put(upImageLoadLocalMedia.get(0), new File(upImageLoadLocalMedia.get(0).getLocalMedia().getPath()));
                                        }
//                                        upLoadImageSingle();
                                    }
                                    addRevelation();
                                } else {
                                    Utility.showToast(getActivity(), getString(R.string.baoliao_upload_image_fail));
                                    dialog.dismiss();
                                }
                            } catch (Exception e) {
                                dialog.dismiss();
                            }
                        }

                        @Override
                        public void onError(@NotNull Throwable e) {
                            if (getActivity() == null)
                                return;
                            Utility.showToast(getActivity(), getString(R.string.baoliao_upload_image_fail));
                            dialog.dismiss();
                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        }
    }


    private List<LocalMediaWithState> videoLoadLocalMedia = new ArrayList<>();
    Map<LocalMediaWithState, File> videoFileList = new HashMap<>();
    Map<LocalMediaWithState, ProgressRequestBody.UploadCallbacks> videoProgressMap = new HashMap<>();

    private void submitVideo() {
        if (totalList.size() == 0) {
            return;
        }
        videoLoadLocalMedia.clear();
        videoLoadLocalMedia.addAll(totalList);

        if (videoLoadLocalMedia.size() > 0) {
            videoFileList.clear();
            videoProgressMap.clear();
            for (int i = 0; i < videoLoadLocalMedia.size(); i++) {
                if (videoLoadLocalMedia.get(i).getLocalMedia().isCompressed()) {
                    videoFileList.put(videoLoadLocalMedia.get(i), new File(videoLoadLocalMedia.get(i).getLocalMedia().getCompressPath()));
                } else {
                    videoFileList.put(videoLoadLocalMedia.get(i), new File(videoLoadLocalMedia.get(i).getLocalMedia().getRealPath()));
                }
                videoProgressMap.put(videoLoadLocalMedia.get(i), new Progress(videoLoadLocalMedia.get(i)));
            }

            submitVideoAudioSingle();
        }
    }

    /**
     * 多文件上传
     */
    private void submitVideoAudioSingle() {
        Map<String, RequestBody> map = new HashMap<>();
//        map.put("TenantID", VMSApi.convertToRequestBody(getString(R.string.tenantid)));
//        map.put("type", VMSApi.convertToRequestBody("video"));
        String url = "servlet/BlUploadServlet?TenantID=" + getString(R.string.tenantid) + "&type=video";
//        VMSApi.getBlApi().uploadVideo(url, map, VMSApi.filesToMultipartBodyParts(videoFileList, videoProgressMap)).enqueue(new Callback<SubmitVideoReturnData>() {
//        map.put("catalogId", CrmsApi.convertToRequestBody(selectCatalog.getId()+""));
        CrmsApi.getCrmsApi(getActivity()).revealFileUpload(map, VMSApi.filesToMultipartBodyParts(videoFileList, videoProgressMap)).enqueue(new Callback<MulFileUpload>() {
            @Override
            public void onResponse(Call<MulFileUpload> call, Response<MulFileUpload> response) {
                if (getActivity() == null)
                    return;
                try {
                   
                    if (response.body().getState() == 200) {
                        List<MulFileUpload.DataBean> data = response.body().data;
                        for (int i = 0; i < data.size(); i++) {
                            ResourceMode mode = new ResourceMode(data.get(i).previewDomain + data.get(i).storageId + data.get(i).resourceUrl, data.get(i).keyFrame, 2, "");
                            String type = "";
                            ResourceModeNew modeNew;
                            if (data.get(i).stuff.equals("mp4")) {
                                type = "video";
                                modeNew = new ResourceModeNew(type, "", "", data.get(i).contentSourceId);
                            } else {
                                type = "image";
                                modeNew = new ResourceModeNew(type, data.get(i).previewDomain + data.get(i).storageId + data.get(i).resourceUrl, data.get(i).contentSourceId, "");
                            }
                            resourceModes.add(mode);
                            resourceModesNew.add(modeNew);
                        }

                        videoFileList.clear();
                        videoProgressMap.clear();
                        addRevelation();
                    } else {
                        Utility.showToast(getActivity(), getString(R.string.baoliao_upload_video_fail));
                        dialog.dismiss();
                    }
                } catch (Exception e) {
                    dialog.dismiss();
                }
            }

            @Override
            public void onFailure(Call<MulFileUpload> call, Throwable t) {
                if (getActivity() == null)
                    return;
                Utility.showToast(getActivity(), getString(R.string.baoliao_upload_video_fail));
                dialog.dismiss();
            }
        });
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        dataInvoker.destory();
    }

    /**
     * 提交爆料
     */
    private void addRevelation() {
        if (selectCatalog == null) {
            ToastUtil.show(getActivity(), R.string.baoliao_get_catalog_fail);
            return;
        }
        JSONArray array = JSONArray.parseArray(JSON.toJSONString(resourceModesNew));

        UserInfo userInfo = UserInfo.getUserInfo(getActivity());
        String content = mEditText.getText().toString();
        String name = nameEditText.getText().toString();
        if (TextUtils.isEmpty(name))
            name = userInfo.getNickname();
        String phone = phoneEditText.getText().toString();
        if (TextUtils.isEmpty(phone))
            phone = userInfo.getMobile();
        String location = locationEditText.getText().toString();

        if (TextUtils.isEmpty(location)) {
            Address address = AppFactoryGlobalConfig.getAddress();
            if (address != null) {
                if (baoLiaoLayerField.locationMust) {
                    location = address.address;
                } else {
                    location = "";
                }
            }
        }

        String latitude = "";
        String longitude = "";
        if (poiInfo == null) {
            latitude = AppFactoryGlobalConfig.getLatitude();
            longitude = AppFactoryGlobalConfig.getLongitude();
        } else {
            if (poiInfo.location == null) {
                latitude = "";
                longitude = "";
            } else {
                latitude = "" + poiInfo.location.latitude;
                longitude = "" + poiInfo.location.longitude;
            }
        }
        JSONObject object = new JSONObject();
        try {
            object.put("title", content);
            object.put("tipImage", userInfo.getAvatar());
            object.put("tipUsername", name);
            object.put("tipUserId", userInfo.getUserid());
            object.put("tipoffTypeId", selectCatalog.getId());
            object.put("id", "");
            object.put("appId", AppFactoryGlobalConfig.getAppServerConfigInfo(getContext()).getCms_app_id());
            object.put("shortTitle", "");
            object.put("shortTitleStyle", array.toString());
            object.put("tipPhone", phone);
            object.put("tipEmail", etEmail.getText().toString());
            object.put("tipAddress", location);
            object.put("tipPerson", TextUtils.isEmpty(etRealName.getText().toString()) ? userInfo.getRealName() : etRealName.getText().toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), object.toString());
        SpiderCmsApi.getSpiderCmsApi(getActivity()).
                addRevelation(getString(R.string.tenantid), body)
                .enqueue(new Callback<SubmitRevelationReturnData>() {
                    @Override
                    public void onResponse(Call<SubmitRevelationReturnData> call, Response<SubmitRevelationReturnData> response) {
                        if (getActivity() == null)
                            return;
                        dialog.dismiss();
                        mEditText.setBackgroundColor(Color.TRANSPARENT);
                    
                        if (response.body().getState() == 200) {
                            Utility.showToast(getActivity(), response.body().getMessage());
                            deleteDraft();
                            getActivity().finish();
                        } else {
                            if (response.body().getState() == 400) {
                                Utility.showToast(getActivity(), response.body().getMessage());
                            } else {
                                Utility.showToast(getActivity(), "网络异常，请检查网络");
                                mEditText.setBackgroundResource(R.drawable.baoliao_incorrect_word_bg);
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<SubmitRevelationReturnData> call, Throwable t) {
                        dialog.dismiss();
                        Utility.showToast(getActivity(), "网络异常，请检查网络");
                    }
                });

    }

    public void deleteDraft() {
        MMKV.defaultMMKV().remove("baoliao_draft");
    }

    public String getJson() {
        DraftModel draftModel = new DraftModel();
        draftModel.setCatalog(selectCatalog);
        draftModel.setContent(mEditText.getText().toString());
        draftModel.setImgs(totalList);
        draftModel.setPhoneNum(phoneEditText.getText().toString());
        draftModel.setAddress(locationEditText.getText().toString());
        draftModel.setUserName(nameEditText.getText().toString());
        draftModel.setRealName(etRealName.getText().toString());
        draftModel.setEmail(etEmail.getText().toString());
        String listJson = GsonUtils.toJson(draftModel);
        return listJson;
    }

    public void seveDraft() {
        MMKV.defaultMMKV().putString("baoliao_draft", getJson());
    }

    public boolean isBaoLiu() {
        if (totalList.size() == 0 &&
                TextUtils.isEmpty(mEditText.getText().toString()) &&
                TextUtils.isEmpty(locationEditText.getText().toString()) &&
                TextUtils.isEmpty(etRealName.getText().toString()) &&
                TextUtils.isEmpty(etEmail.getText().toString())) {
            return false;
        }
        return true;
    }


    class Progress implements ProgressRequestBody.UploadCallbacks {
        LocalMediaWithState localMedia;

        public Progress(LocalMediaWithState localMedia) {
            this.localMedia = localMedia;
        }

        @Override
        public void onProgressUpdate(int percentage) {
            int position = totalList.indexOf(localMedia);
            mAdapter.getSelectList().get(position).setProgress(percentage);
            mAdapter.notifyDataSetChanged();
        }

        @Override
        public void onError() {
            Log.w(TAG, "Progress  onError ");
        }

        @Override
        public void onFinish() {
            Log.w(TAG, "Progress  onFinish position");
            int position = totalList.indexOf(localMedia);
            mAdapter.getSelectList().get(position).setProgress(100);
            mAdapter.getSelectList().get(position).setState(true);
            mAdapter.notifyDataSetChanged();
        }
    }
}